package com.shuhe.interceptor;

import com.shuhe.metastore.MetaMysql;
import com.shuhe.utils.HttpUtils;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;


public class ClientInterceptor {
    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */

    private static Logger log = Logger.getLogger(ClientInterceptor.class);

    public static boolean preHandle(HttpServletRequest request, HttpServletResponse response) {
        String clientIp = HttpUtils.getIpAddr(request);
        log.info("client ask:" + clientIp);
        Connection metaConn = null;
        try {
            metaConn = MetaMysql.connect();
            String sql = "select client_ip from mxgc_client_config";
            ResultSet rs = MetaMysql.querySql(metaConn, sql);
            ArrayList<String> ips = new ArrayList<String>();
            while (rs.next()) {
                ips.add(rs.getString("client_ip"));
            }
            if (ips.indexOf(clientIp) >= 0) {
//            return true;  //如果设置为true时，请求将会继续执行后面的操作
                return true;
            } else {
//            return false; //如果设置为false时，被请求时，拦截器执行到此处将不会继续操作
                log.info("'msg':'非法客户端访问[" + clientIp + "]'");
                return false;
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (metaConn != null) {
                try {
                    metaConn.close();
                } catch (Exception ex) {
                    log.error(ex.getMessage());
                }
            }

        }
        return false;
    }

}